package com.wyz.saas.common.map

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.graphics.Point
import android.os.Bundle
import android.util.DisplayMetrics
import android.util.Log
import android.view.GestureDetector
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.core.view.children
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.atom.map.WorldWind
import com.atom.map.WorldWindow
import com.atom.map.controller.BasicWorldWindowController
import com.atom.map.core.tile.ImageTile
import com.atom.map.core.tile.Tile
import com.atom.map.core.tile.TileFactory
import com.atom.map.geom.Sector
import com.atom.map.layer.BackgroundLayer
import com.atom.map.layer.RenderableLayer
import com.atom.map.renderable.ImageOptions
import com.atom.map.renderable.ImageSource
import com.atom.map.renderable.TiledSurfaceImage
import com.atom.map.util.Level
import com.atom.map.util.LevelSet
import com.atom.map.util.LevelSetConfig
import com.atom.module.mvvm.base.AbstractViewModelFactory
import com.atom.module.mvvm.wight.recycler.base.AbstractBaseRecyclerAdapterListener
import com.atom.module.mvvm.wight.recycler.base.BaseRecyclerAdapter
import com.wyz.saas.api.app.ApiButton
import com.wyz.saas.api.map.MapOverlayManager
import com.wyz.saas.common.R
import com.wyz.saas.common.base.AbstractApiFragment
import com.wyz.saas.common.databinding.CellMapPickListBinding
import com.wyz.saas.common.databinding.FragmentMapBinding
import com.wyz.saas.common.impl.EmptyApiModel
import java.io.File

/**
 * Map的Fragment
 * TODO 使用MKVV 进行本地按钮的持久化
 */
open class MapFragment : AbstractApiFragment<FragmentMapBinding, MapViewModel>() {
    private val key: String = "05f9d29cd248ba2fe566446ef123775c"
    private val name: String = "img"
    var wwd: WorldWindow? = null
    var manager: MapOverlayManager? = null

    override fun initContentView(
        inflater: LayoutInflater?,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): Int {
        return R.layout.fragment_map
    }

    override fun initViewModel(): MapViewModel {
        val factory = object : AbstractViewModelFactory() {
            override fun <T : ViewModel?> create(modelClass: Class<T>): T {
                if (modelClass.isAssignableFrom(MapViewModel::class.java)) {
                    return MapViewModel(EmptyApiModel()) as T
                }
                return modelClass.newInstance()
            }
        }
        return ViewModelProvider(this, factory).get(MapViewModel::class.java)
    }

    override fun initViewBinding(
        binding: FragmentMapBinding?,
        viewModel: MapViewModel?
    ) {
        super.initViewBinding(binding, viewModel)
        binding?.root?.also { root ->
            wwd = WorldWindow(root.context)
            root.findViewById<FrameLayout>(R.id.map_frame_layout).addView(wwd, 0)
            wwd?.layers?.addLayer(BackgroundLayer())
            //wwd?.layers?.addLayer(BlueMarbleLandsatLayer())
            wwd?.layers?.addLayer(createRenderableLayer())
            // 添加到地图平面的按钮
            wwd?.worldWindowController = MapController()
        }
    }

    protected open fun createRenderableLayer(): RenderableLayer {
        val renderableLayer = RenderableLayer()
        renderableLayer.displayName = ("天地图影像底图")
        renderableLayer.pickEnabled = (false)
        val levelsConfig = LevelSetConfig(null, 45.0, 16, 256, 256)
        val surfaceImage = TiledSurfaceImage()
        surfaceImage.levelSet = (LevelSet(levelsConfig))
        surfaceImage.tileFactory = object : TileFactory {
            override fun createTile(sector: Sector, level: Level, row: Int, column: Int): Tile {
                var y = row
                val z = level.levelNumber + 3
                y = (1 shl z - 1) - 1 - y
                val tile = ImageTile(sector, level, row, column)
                val tileUrl = tileUrl(key, name, column, y, z)
                Log.e("TiandituLayerActivity", "tileUrl = $tileUrl")
                val cachePath: String = cachePath(name, column, y, z)
                tile.imageSource = (ImageSource.fromUrl(tileUrl))
                return tile
            }
        }
        surfaceImage.imageOptions = (ImageOptions(
            WorldWind.RGBA_8888
        ))
        renderableLayer.addRenderable(surfaceImage)
        return renderableLayer
    }

    private fun cachePath(layer: String, x: Int, y: Int, z: Int): String {
        return layer + File.separator + z + File.separator + y + "." + x + ".jpg"
    }

    private fun tileUrl(
        key: String,
        layer: String,
        x: Int,
        y: Int,
        z: Int
    ): String {
        var url =
            "https://t" + (Math.random() * 8).toInt() + ".tianditu.gov.cn/" + layer + "_c" + "/wmts?SERVICE=WMTS"
        url += "&REQUEST=GetTile"
        url += "&VERSION=1.0.0"
        url += "&LAYER=$layer"
        url += "&STYLE=default"
        url += "&TILEMATRIXSET=c"
        url += "&FORMAT=tiles"
        url += "&TILEMATRIX=$z"
        url += "&TILEROW=$y"
        url += "&TILECOL=$x"
        url += "&tk=$key"
        return url
    }

    /**
     * 初始化TableLayout 用于自定义设置按键
     */
    private fun createTableLayout(
        contentView: View?, visit: Int
    ) {
        contentView?.findViewById<FrameLayout>(R.id.map_frame_layout)?.also { frameLayout ->
            frameLayout.findViewById<TableLayout>(R.id.tag_map_table_layout)?.also { tableLayout ->
                tableLayout.visibility = visit
            } ?: also {
                val point = Point()
                val metric = DisplayMetrics()
                val display = requireActivity().windowManager.defaultDisplay
                display.getSize(point)
                display.getMetrics(metric)
                // TableView adapter Data
                val buttonLayout = arrayOfNulls<Array<ApiButton?>>(8)
                for (idx in 0..7) {
                    buttonLayout[idx] = arrayOfNulls(5)
                }

                val table = TableLayout(context)
                table.setBackgroundColor(resources.getColor(R.color.map_table_bg))
                table.id = R.id.tag_map_table_layout
                // 计算单位宽高
                val itemH = point.y / buttonLayout.size
                // 添加button
                buttonLayout.forEachIndexed { y, arrayButton ->
                    arrayButton?.also { array ->
                        val row = TableRow(context)
                        row.layoutParams = TableLayout.LayoutParams()
                        val itemW = point.x / array.size
                        array.forEachIndexed { x, button ->
                            // 初始化button按钮 如果为空 则代表可添加的
                            button?.also {

                            }
                            val linearLayout =
                                LayoutInflater.from(context).inflate(R.layout.cell_map_list, null)
                            linearLayout.setOnClickListener { view ->
                                view.tag?.also {
                                    view.tag = null
                                    view.findViewById<ImageView>(R.id.map_item_icon)
                                        .setImageResource(R.mipmap.icon_map_button_add)
                                } ?: also {
                                    dialog(object : PickListener<ApiButton> {
                                        override fun pick(t: ApiButton) {
                                            view.findViewById<ImageView>(R.id.map_item_icon)
                                                .setImageBitmap(
                                                    t.getBitmap()
                                                )
                                            view.tag = t
                                            buttonLayout[y]?.set(x, t)
                                        }
                                    })
                                }
                            }
                            row.addView(linearLayout, itemW, itemH)
                        }
                        table.addView(
                            row,
                            ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, itemH)
                        )
                    }
                }
                frameLayout.addView(table)
            }
        }
    }

    override fun onBackPressed(): Boolean {
        contentView?.also { contentView ->
            contentView.findViewById<TableLayout>(R.id.tag_map_table_layout)?.also { tableLayout ->
                if (tableLayout.visibility == View.VISIBLE) {
                    tableLayout.children.forEach { tablerow ->
                        if (tablerow is TableRow) {
                            tablerow.children.forEach { itemView ->
                                val tag = itemView.tag
                                if (tag is ApiButton) {
                                    val linearLayout =
                                        LayoutInflater.from(context)
                                            .inflate(R.layout.cell_map_list, null)
                                    linearLayout.findViewById<ImageView>(R.id.map_item_icon)
                                        ?.setImageBitmap(
                                            tag.getBitmap()
                                        )
                                    linearLayout.setOnClickListener {
                                        tag.onViewClick(this@MapFragment, it)
                                    }
                                    // TODO 进行注册 ui更新的通知
//                                    val sub = object : AbstractSubscrber<ApiButton>() {
//                                        override fun call(news: News<ApiButton>) {
//                                            linearLayout.post {
//                                                linearLayout.findViewById<ImageView>(R.id.map_item_icon)
//                                                    ?.setImageBitmap(
//                                                        news.value().getBitmap()
//                                                    )
//                                            }
//                                        }
//                                    }
//                                    apiContext().getImpl(Center::class.java)?.register(
//                                        tag.style(), sub
//                                    )
//                                    listSub.add(sub)
                                    val headParams: FrameLayout.LayoutParams =
                                        FrameLayout.LayoutParams(
                                            itemView.width,
                                            itemView.height
                                        )
                                    val array = IntArray(2)
                                    itemView.getLocationOnScreen(array)
                                    headParams.setMargins(
                                        array[0],
                                        array[1],
                                        0,
                                        0
                                    )
                                    linearLayout.layoutParams = headParams
                                    // TODO 进行设置tag
                                    //linearLayout.tag = sub
                                    contentView.findViewById<FrameLayout>(R.id.map_frame_layout)
                                        ?.addView(linearLayout)
                                }
                            }
                        }
                    }
                    createTableLayout(contentView, View.GONE)
                    return true
                }
            }
        }
        return super.onBackPressed()
    }

    inner class MapController : BasicWorldWindowController() {
        private var idx = 0
        private var time = 0L
        private var pickGestureDetector =
            GestureDetector(activity, object : GestureDetector.SimpleOnGestureListener() {
                override fun onDown(e: MotionEvent?): Boolean {
                    if (time == 0L) {
                        time = System.currentTimeMillis()
                    } else {
                        val currentTimeMillis = System.currentTimeMillis()
                        if (currentTimeMillis - time > 1000) {
                            time = 0L
                            idx = 0
                        } else {
                            time = currentTimeMillis
                            if (idx >= 5) {
                                idx = 0
                                time = 0L
                                contentView?.post {
                                    // 移除屏幕内tag = any的按钮
                                    contentView?.findViewById<FrameLayout>(R.id.map_frame_layout)
                                        ?.also { frameLayout ->
                                            val childCount = frameLayout.childCount;
                                            frameLayout.removeViews(1, childCount - 1)
                                        }
                                    createTableLayout(contentView, View.VISIBLE)
                                }
                            } else {
                                idx++
                            }
                        }
                    }
                    return false
                }
            })

        override fun onTouchEvent(event: MotionEvent): Boolean {
            val consumed = pickGestureDetector.onTouchEvent(event)
            return if (!consumed) {
                super.onTouchEvent(event)
            } else consumed
        }
    }

    class ViewHolder(viewBinding: CellMapPickListBinding) :
        BaseRecyclerAdapter.ViewHolder<ApiButton, CellMapPickListBinding>(viewBinding) {
        private var image: ImageView? = null
        private var label: TextView? = null

        init {
            image = itemView.findViewById(R.id.pick_item_icon)
            label = itemView.findViewById(R.id.pick_item_label)
        }

        override fun onBind(data: ApiButton) {
            image?.setImageBitmap(data.getBitmap())
            label?.text = data.getLabel()
        }
    }

    interface PickListener<T> {
        fun pick(t: T)
    }

    private fun dialog(listener: PickListener<ApiButton>) {
        val customizeDialog = AlertDialog.Builder(context)
        val recycle = RecyclerView(requireContext())
        customizeDialog.setTitle("按钮选择")
        customizeDialog.setView(recycle)
        customizeDialog.setPositiveButton(
            "取消"
        ) { dialog, which -> // 获取EditView中的输入内容
            dialog.dismiss()
        }
        val show = customizeDialog.show()
        recycle.layoutManager = LinearLayoutManager(context)
        recycle.adapter = object :
            BaseRecyclerAdapter<ApiButton, CellMapPickListBinding>(loadItemValues(), null) {
            override fun getItemViewType(position: Int, data: ApiButton): Int {
                return R.layout.cell_map_pick_list
            }

            override fun onCreateViewHolder(
                binding: CellMapPickListBinding,
                viewType: Int
            ): ViewHolder<ApiButton, CellMapPickListBinding> {
                return MapFragment.ViewHolder(binding)
            }

        }.also {
            it.listener =
                object : AbstractBaseRecyclerAdapterListener<ApiButton, CellMapPickListBinding>() {
                    override fun onItemClick(viewHolder: BaseRecyclerAdapter.ViewHolder<ApiButton, CellMapPickListBinding>) {
                        super.onItemClick(viewHolder)
                        viewHolder.mData?.also { bt ->
                            listener.pick(bt)
                        }
                        show.dismiss()
                    }
                }
        }
    }

    override fun onFirst() {
        super.onFirst()
        // 初始化button按钮
        loadItemValues()
        // 获取图层管理器
        manager = apiContext().getImpl(MapOverlayManager::class.java)
        // 设置地图控件
        manager?.setMapView(wwd)
    }

    var listButton: List<ApiButton>? = null

    @SuppressLint("LongLogTag")
    private fun loadItemValues(): List<ApiButton> {
        if (listButton == null) {
            val tempList = mutableListOf<ApiButton>()
            val apiImplContext = apiContext()
            for (cls in apiImplContext.getApis(ApiButton::class.java)) {
                try {
                    val button = apiImplContext.newApi(cls)
                    if (button != null && button.isAuthorized() && button.isMapButton()) {
                        tempList.add(button)
                    }
                } catch (ignored: Exception) {
                }
            }
            tempList.sortWith(object : Comparator<ApiButton> {
                override fun compare(o1: ApiButton?, o2: ApiButton?): Int {
                    val button1 = o1 ?: return 0
                    val button2 = o2 ?: return 0
                    return button1.getLabel().compareTo(button2.getLabel())
                }
            })
            listButton = tempList
        }
        return listButton!!
    }

    override fun onStart() {
        super.onStart()
        manager?.onStart()
    }

    override fun onResume() {
        super.onResume()
        wwd?.onResume()
    }

    override fun onPause() {
        wwd?.onPause()
        super.onPause()
    }

    override fun onStop() {
        super.onStop()
        manager?.onStop()
    }

    override fun onDetach() {
        super.onDetach()
        // 移除地图控件
        manager?.setMapView(null)
    }
}